﻿using System;
using UtfprLibrary.ComponentModel.Security;

namespace UtfprLibrary.Windows.Forms.ComponentModel.Security {
    /// <summary>
    /// TODO
    /// </summary>
    internal class UtfprSecurity : IUtfprSecurity {
        #region Singleton

        private UtfprSecurity() { }

        private static UtfprSecurity _utfprSecurity;
        public static UtfprSecurity Instance {
            get {
                if (_utfprSecurity == null) {
                    _utfprSecurity = new UtfprSecurity();
                }

                return _utfprSecurity;
            }
        }

        #endregion

        #region Properties

        private IUtfprUser _user = null;
        public IUtfprUser User {
            get {
                return _user;
            }
        }

        #endregion

        #region IUtfprSecurity Members

        public bool IsUserConected {
            get {
                if (this._user == null) {
                    return false;
                } else {
                    return true;
                }
            }
        }

        public void DisconnectCurrentUser() {
            this._user = null;
        }

        public void ConnectUser(IUtfprUser user) {
            _user = user;
        }

        /// <summary>
        /// Exibe o formulario de Login.
        /// Se nenhum formulario de Login for previamente configurado para ser exibido,
        /// um formulario default será utilizado.
        /// </summary>
        public void ShowFormLoginDefault() {
            if (!UtfprSecurity.Instance.IsUserConected) {

                if (UtfprApplication.Instance.FormLoginDefault.IsDisposed) {
                    InvokeSetDefaultLogin();
                }
                                
                UtfprApplication.Instance.FormLoginDefault.ShowDialog();
            }
        }

        #endregion

        /// <summary>
        /// Invoca o método "SetDefaulLogin" que fica responsável de reinstanciar 
        /// o objeto que estava no estado "Disposed".
        /// </summary>
        private void InvokeSetDefaultLogin() {
            typeof(IUtfprFormLoginConfiguration)
                .GetMethod("SetFormLoginDefault")
                .MakeGenericMethod(new Type[] { UtfprApplication.Instance.FormLoginDefault.GetType() })
                .Invoke(UtfprApplication.Instance, null);
        }
    }
}
